package com.yinxing.framework.aspectj;

import com.yinxing.framework.annotation.DataSource;
import com.yinxing.framework.datasource.DataSourceHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
@Order(AspectOrder.DataSourceAspect)
public class DataSourceAspect {

    @Around("@annotation(com.yinxing.framework.annotation.DataSource)")
    public Object around(ProceedingJoinPoint point) throws Throwable {

        final Object result;

        MethodSignature signature = (MethodSignature) point.getSignature();
        DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
        DataSourceHolder.setDataSourceType(dataSource.value().name());
        try {
            result = point.proceed();
        } finally {
            DataSourceHolder.clearDataSourceType();
        }
        return result;
    }
}
